import { defineStore } from "pinia";
import { useUserStore } from "./useUserStore";
import router from "@/router";
import { useCourseData } from "@/store/useCourse";
import { objToQueryString } from "@/utils/url";
interface LocationParams {
  code?: string;
  inviteCode?: string;
  rId?: string;
  sId?: string;
  scene?: string;
  channel?: string;
  sRId?: string;
  oPd?: string;
  pd?: string;
  from?: string;
  ic?: string;
}
export const useLocationParams = defineStore("locationParams", () => {
  let locationParams = new URLSearchParams(window.location.search);
  function getParam(key: string): string | null {
    return locationParams.get(key);
  }

  function setParam(key: string, value: string): void {
    locationParams.set(key, value);
    window.history.replaceState({}, "", "?" + locationParams.toString());
    updateParam();
  }

  function removeParam(key: string): void {
    locationParams.delete(key);
    window.history.replaceState({}, "", "?" + locationParams.toString());
    updateParam();
  }

  function updateParam(): void {
    locationParams = new URLSearchParams(window.location.search);
  }

  function getAllParams(): LocationParams {
    const params: LocationParams = {};
    locationParams.forEach((value, key) => {
      params[key as keyof LocationParams] = value;
    });
    return params;
  }

  return {
    getParam,
    setParam,
    removeParam,
    updateParam,
    getAllParams
  };
});

export const useLocation = defineStore("location", () => {
  const userStore = useUserStore();
  const { checkInviteCode, entryRoom } = useCourseData();
  const { getAllParams, removeParam } = useLocationParams();
  const resolveLocation = async () => {
    try {
      const allParams = getAllParams();
      if (allParams.oPd === "1" && allParams.pd && !allParams.from) {
        router.push({ name: "CheckPassword", query: { ...allParams } });
      } else if (allParams["code"]) {
        // if (!userStore.isAuthenticated()) {
        userStore.clearUser();
        if (allParams.from) {
          const from = allParams.from;
          removeParam("from");
          const fromUrl = `${from}?${objToQueryString(getAllParams())}`;
          window.location.href = fromUrl;
        } else {
          await userStore.login({ ...allParams });
          removeParam("code");
          resolveLocation();
        }
        // location.reload();
        // }
        return;
      } else if (allParams["inviteCode"]) {
        // const data = await checkInviteCode(allParams["inviteCode"]);
        // await entryRoom(21);
        // if (data) {
        if (userStore.isAuthenticated()) {
          router.push({
            name: "Course",
            query: { ...allParams }
          });
        } else {
          router.replace({ name: "Login", query: { ...allParams } });
        }
        // }
        return;
      }
    } catch (error) {
      console.error("Error resolving location:", error);
    }
  };
  return {
    resolveLocation
  };
});
